package configlogic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/config"
	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/config"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type EditConfigInoutLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	repo    *config.InoutModel
	logRepo *config.ConfigInoutTypeLog
}

func NewEditConfigInoutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EditConfigInoutLogic {
	return &EditConfigInoutLogic{
		ctx:     ctx,
		svcCtx:  svcCtx,
		Logger:  logx.WithContext(ctx),
		repo:    config.NewInoutModel(ctx, svcCtx.Db),
		logRepo: config.NewConfigInoutTypeLog(ctx, svcCtx.Db),
	}
}

// EditConfigInout 编辑
func (l *EditConfigInoutLogic) EditConfigInout(in *rpc.EditConfigInoutRq) (*rpc.EditConfigInoutReps, error) {
	if in.GetTypeId() != 0 {
		var record *schema.ConfigInoutType
		bl, record, err := l.repo.Exists(in.GetTypeId())
		if err != nil {
			return nil, err
		}
		if bl == true { // 判断type_id是否重复
			if in.GetId() == 0 || in.GetId() != record.Id {
				err1 := errors.New(fmt.Sprintf("Type id [%v] already exists.", in.GetTypeId()))
				l.Logger.Error(err1.Error())
				return nil, err1
			}
		}
	}
	data := schema.ConfigInoutType{
		Name:    in.GetName(),
		TypeId:  in.GetTypeId(),
		Value:   in.GetValue(),
		TagType: int(in.GetTagType()),
		Remark:  in.GetRemark(),
	}
	var logData schema.ConfigInoutTypeLog
	if in.GetId() == 0 { // 新增
		data.CreatedUid = in.GetCreateUid()
		configId, err3 := l.repo.Add(data)
		if err3 != nil {
			return nil, err3
		}
		logData.ConfigId = configId
	} else { // 更新或删除
		// 记录日志数据
		logData.ConfigId = in.GetId()
		oldValue, _ := l.repo.FindById(in.GetId())
		oldValueStr, _ := json.Marshal(oldValue)
		logData.OldValue = string(oldValueStr)

		if in.DeletedAt != 0 { // 删除
			data.DeletedAt = in.GetDeletedAt()
		}
		data.UpdatedUid = in.GetUpdateUid()

		err4 := l.repo.Edit(in.GetId(), data)
		if err4 != nil {
			l.Logger.Error(err4.Error())
			return nil, err4
		}
	}

	newValue, _ := l.repo.FindById(logData.ConfigId) // 获取新数据
	newValueStr, _ := json.Marshal(newValue)
	logData.NewValue = string(newValueStr) // 日志
	logData.CreatedUid = in.GetCreateUid()
	logData.Ip = in.GetIp()
	_, err5 := l.logRepo.Add(logData)
	if err5 != nil {
		return nil, err5
	}
	return &rpc.EditConfigInoutReps{}, nil
}
